.PHONY: all
TOP := $(dir $(lastword $(MAKEFILE_LIST)))
BUILD_DIR = $(TOP)build
SRC_DIR = $(TOP)src
INCLUDES = -I$(TOP)inc -I$(TOP)build

CC = gcc
CFLAG = -c -g $(INCLUDES)
CPP = g++
LD = g++
LDFLAGS = -lfl -ly

#OBJS = lex.o parser.o visitor.o expr.o main.o stmt.o tree.o symbol.o debug.o opcode.o
SOURCES = $(notdir $(wildcard $(SRC_DIR)/*.cpp) $(wildcard $(SRC_DIR)/opt/*.cpp))
OBJS = $(SOURCES:.cpp=.o) parser.o lex.o
DEPS = $(patsubst %.cpp,$(BUILD_DIR)/%.d,$(SOURCES))

.SILENT:

.SUFFIXES:

VPATH=$(SRC_DIR):$(SRC_DIR)/opt

all: plac

clean:
	rm -f $(BUILD_DIR)/*
	rm -f $(TOP)plac

plac: $(foreach n,$(OBJS),$(BUILD_DIR)/$(n))
	@echo "[LINK]: $^..."
	$(LD) -o $(TOP)$@ $^ $(LDFLAGS)

$(BUILD_DIR)/%.d:%.cpp
	@echo "[DEP]: $<..."
	$(CPP) $(INCLUDES) -MM $< | sed 's,^\(.*\.o\),$(BUILD_DIR)\/\1 $@,' > $@

$(BUILD_DIR)/parser.cpp:parser.yy
	@echo "[BISON]: $<..."
	bison -g -t -v -d $< -o $@

$(BUILD_DIR)/parser.o:$(BUILD_DIR)/parser.cpp
	@echo "[CPP]: $<..."
	$(CPP) $(CFLAG) -o $@ $<

$(BUILD_DIR)/lex.c:lex.l $(BUILD_DIR)/parser.cpp
	@echo "[LEX]: $<..."
	flex -o $@ $<

$(BUILD_DIR)/lex.o:$(BUILD_DIR)/lex.c
	@echo "[C]: $<..."
	$(CPP) $(CFLAG) -o $@ $<

$(BUILD_DIR)/%.o:%.cpp
	@echo "[CPP]: $<..."
	$(CPP) $(CFLAG) -o $@ $<

-include $(DEPS)

check-syntax:
	$(CPP) $(CFLAG) -w -pedantic -fsyntax-only $(CHK_SOURCES)

